const crypto = require("crypto");
const path = require("path");
const fs = require("fs");
const formidable = require("formidable");
const { insertUser, isUserExist } = require("../model/user");

const secret = "abcdefg";

const register = (req, resp) => {
  var form = new formidable.IncomingForm();
  form.uploadDir = path.resolve(__dirname, "../public/images");
  form.keepExtensions = true;
  form.parse(req, function(err, fields, files) {
    if (err) throw err;
    else {
      const { username, password } = fields;
      const avatarPath = files.avatar.path;
      const { base } = path.parse(avatarPath);
      isUserExist({ username })
        .then(users => {
          if (users.length > 0) {
            fs.unlink(avatarPath, err => {
              if (err) throw err;
              else {
                // 用户已存在
                resp.json({
                  code: 300,
                  body: {
                    msg: "用户已存在"
                  }
                });
              }
            });
          } else {
            // 用户不存在，可以注册
            const hash = crypto
              .createHmac("sha256", secret)
              .update(password)
              .digest("hex");
            insertUser({ username, password: hash, avatar: "/images/" + base })
              .then(user => {
                resp.json({
                  code: 200,
                  body: {
                    msg: "注册成功",
                    user
                  }
                });
              })
              .catch(err => {
                resp.json({
                  code: 400,
                  body: {
                    msg: "网络错误，请重试",
                    err
                  }
                });
              });
          }
        })
        .catch(err => {
          resp.json({
            code: 400,
            body: {
              msg: "网络错误，请重试",
              err
            }
          });
        });
    }
  });
  // const { username, password } = req.body;
};
const login = (req, resp) => {
  const { username, password, expires } = req.body;
  const hash = crypto
    .createHmac("sha256", secret)
    .update(password)
    .digest("hex");
  isUserExist({ username, password: hash }).then(users => {
    if (users.length > 0) {
      const { avatar } = users[0];
      //登陆成功，后端存一个会话存储
      //后端在做session存储的时候就会有一个sessionId，是一个随机字符串
      //这个字符串会随着resp.json一起响应给前端，还会自动存到前端的cookie里
      if (expires === "7") {
        req.sessionOptions = {
          maxAge: 7 * 24 * 3600 * 1000
        };
      }
      req.session = {
        isLogin: true,
        username,
        avatar
      };
      resp.json({
        code: 200,
        msg: "登录成功"
      });
    } else {
      resp.json({
        code: 400,

        msg: "用户名或者密码错误"
      });
    }
  });
};
const isLogin = (req, resp) => {
  if (req.session.isLogin) {
    //已登录
    resp.json({
      code: 200,
      body: {
        msg: "已登录",
        username: req.session.username,
        avatar: req.session.avatar
      }
    });
  } else {
    resp.json({
      code: 400,

      msg: "未登录"
    });
  }
};

const unLogin = (req, resp) => {
  //清空session
  req.session = null;
  resp.json({
    code: 200,
    msg: "退出成功"
  });
};
module.exports = {
  register,
  login,
  isLogin,
  unLogin
};
